package com.app.controller.miniprogram;

import com.app.common.Result;
import com.app.model.GoodsModel;
import com.app.model.UserModel;
import com.app.service.GoodsService;
import com.app.service.UserService;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@Controller
@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;

    //分类列表
    @GetMapping("/selectTypeList")
    public Result<Object> selectTypeList() {
        return Result.success(goodsService.selectTypeList());
    }

    //列表查询，通过分类、标题关键字筛选
    @GetMapping("/selectGoodsList")
    public Result<Object> selectGoodsList(Integer type, String title, Integer page, Integer limit, Integer villageId) {
        return Result.success(goodsService.selectGoodsList(type, title, page, limit, villageId));
    }

    //查看详情
    @GetMapping("/selectContentById")
    public Result<Object> selectContentById(Integer id) {
        if (id == null || id == 0) {
            return null;
        }
        return Result.success(goodsService.selectContentById(id));
    }

    //立即兑换
    @GetMapping("/redeemNow")
    public Result<Object> redeemNow(Integer id, Integer num, Integer villageId, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.nothingness(token);
        UserModel user = userService.getUserByOpenid(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        if (id == null || id == 0) {
            return Result.error(500, "商品不存在");
        }
        if (user.getIdCard() == null) {
            return Result.error(500, "请先完善个人信息");
        }
        if (user.getVillageId() == 0) {
            return Result.error(406, "您还没有实名认证，认证后即可兑换商品");
        }
        if (!user.getVillageId().equals(villageId) && user.getVillageId() != 0) {
            return Result.error(406, "请到您所在村的积分商城兑换商品");
        }
        GoodsModel goodsModel1 = goodsService.selectContentById(id);
        if (num < 0 || num > goodsModel1.getInventory()) {
            return Result.error(500, "库存不足");
        }
        UserModel userModel = userService.selectUserById(user.getId());
        if (userModel.getIntegral() < goodsModel1.getIntegral() * num) {
            return Result.error(500, "积分不足");
        }
        goodsService.insertGoodsExchange(user, id, num);
        return Result.success("申请成功，等待审核");
    }
}
